package org.jing.core.lang.data;

import org.jing.core.lang.Const;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * Description: 文件大小. <br>
 *
 * @author bks <br>
 * @since 2024-07-22 <br>
 */
@SuppressWarnings({ "WeakerAccess", "unused" })
public final class FileSize extends BaseDto {
    private static final String[] UNIT_ARR = { "b", "kb", "mb", "gb", "tb" };

    private static final BigDecimal LEVEL = BigDecimal.valueOf(1024);

    private BigDecimal size;

    private String unit;

    private FileSize() {}

    public BigDecimal getSize() {
        return size;
    }

    public String getUnit() {
        return unit;
    }

    public static FileSize parse(long size) {
        return parse(size, 2);
    }

    public static FileSize parse(long size, int scale) {
        FileSize fileSize = new FileSize();
        fileSize.size = new BigDecimal(size);
        int unit = 0;
        BigDecimal all = BigDecimal.valueOf(size);
        BigDecimal n1, n2 = all, n3 = BigDecimal.valueOf(1);
        while (0 <= (n1 = all.divide(n3 = (n3.multiply(LEVEL)), scale, RoundingMode.HALF_UP)).compareTo(Const.NUM_1)) {
            unit ++;
            n2 = n1;
            if (unit == UNIT_ARR.length - 1) {
                break;
            }
        }
        fileSize.size = n2;
        fileSize.unit = UNIT_ARR[unit];
        return fileSize;
    }
}
